//
//  PeripheryServiceVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/21.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

class PeripheryServiceVC: BaseViewController {
    
    var hasmore = "-999"
    
    var page_total = "-999"
    
    var dataModels : [BusinessActivityModel]?
    
    var isScrollDown = true
    
    var lastOffsetY : CGFloat = 0.0

    
    var strings = ["同城装饰 衣柜门定制15327907101","十区童鑫文具办公打字复印","童鑫文体雪糕批发","室内乳胶漆仿瓷18871032459","12.10栋小凯纱窗衣柜门","20-9配门禁卡换指纹锁，E级锁芯","12区_襄阳光彩百大整体厨房 邹庆","10号楼103茶馆","12区-襄阳佳镜视光中心~配镜中心","十区中国电信，移动","襄阳家和顺美装饰（柯建设)","15#803多力葵花油","外卖奶茶鸡排电话18671070026","12-17灯具开关电线","13号、凤凰i美缝13476416454","12区骄杨教育18371031360","收废品，除渣18771531656","专业室内除甲醛10-15","14栋凡亚轩装饰公司顾问阿慧","12区12栋 平面设计 UI影视","20-902指纹锁.锁芯.门禁卡","20-9配门禁卡换指纹锁，E级锁芯","业主保洁15872207531","13号、凤凰i美缝13476416454","10栋7，复印，文具","12-10专业水电安装","十二区十三美缝保洁装修","12-15王杰奥米龙陶瓷","12-17灯具开关电线","外卖奶茶鸡排电话18671070026","12区-5光彩百大整体厨房和全屋定制","同城装饰 衣柜门定制15327907101","十区童鑫文具办公打字复印","童鑫文体雪糕批发","室内乳胶漆仿瓷18871032459","12.10栋小凯纱窗衣柜门","20-9配门禁卡换指纹锁，E级锁芯","12区_襄阳光彩百大整体厨房 邹庆","10号楼103茶馆","12区-襄阳佳镜视光中心~配镜中心","十区中国电信，移动","襄阳家和顺美装饰（柯建设)","15#803多力葵花油","外卖奶茶鸡排电话18671070026","12-17灯具开关电线","13号、凤凰i美缝13476416454","12区骄杨教育18371031360"]
    
    
    var leftTitles = ["家政服务","装修建材","汽车服务","教育培训","休闲娱乐","婚庆摄影","旅游酒店","餐饮美食","丽人美容"]
    
    var page = -999

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        
        groupTableView.tableFooterView = UIView()
        
        groupTableView.frame = CGRect(x: 0, y: 0, width: 80, height: KScreenH)

        groupTableView.rowHeight = 55
        
        groupTableView.separatorColor = UIColor.clear

        
        groupTableView.backgroundColor = UIColor.white

        groupTableView.contentInset = UIEdgeInsetsMake(ZMNavMaxY + ZMTitlesViewH, 0, 49, 0)
        
        groupTableView.register(UINib(nibName: StringFromClass(classType: NearbyServiceCell.self), bundle: nil), forCellReuseIdentifier: NearbyServiceCell.identifer())

        

        loadData()
        
        
//         plainTableView.estimatedRowHeight = 100
        
        
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: ServiceRightCell.self), bundle: nil), forCellReuseIdentifier: ServiceRightCell.identifer())

        plainTableView.frame = CGRect(x: 82, y: 0, width: KScreenW - 82, height: KScreenH)


        plainTableView.contentInset = UIEdgeInsetsMake(ZMNavMaxY + ZMTitlesViewH, 0, 49, 0)

        plainTableView.rowHeight = 55
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: RightTabelHeaderView.self), bundle: nil), forHeaderFooterViewReuseIdentifier: RightTabelHeaderView.identifer())


//        weak var weakSelf = self
        
//        plainTableView.mj_header =  ZMRefreshHeader.init {
//            
//            weakSelf!.loadData()
//            
//        }
        
//        plainTableView.mj_header.beginRefreshing()
//        
//        plainTableView.mj_footer = ZMRefreshFooter.init{
//            
//            weakSelf!.loadMoreData()
//            
//        }

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}



extension PeripheryServiceVC{
    
    func loadData() {
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=article&a=article_list&ac_id=1", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.page_total = responseObject!["page_total"] as! String
                
                self?.dataModels = [BusinessActivityModel]()
                
                for dic in responseObject!["datas"]!["article_list"] as! [[String : AnyObject]]{
                    
                    self!.dataModels!.append(BusinessActivityModel(dic: dic))
                    
                }
                
                if self!.dataModels!.count == 0{
                    
                    self?.showLogoView(text : "暂无通知...")
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                }else{
                    
                    self!.cachePictures()
                    
                }
                
                
            }else{
                
                self!.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
            }
            
        }
        
    }
    
    
    
    func loadMoreData() {
        
        page += 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=article&a=article_list&ac_id=1", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.page_total = responseObject!["page_total"] as! String
                
                var tempArray = [BusinessActivityModel]()
                
                for dic in responseObject!["datas"]!["article_list"] as! [[String : AnyObject]]{
                    
                    let tempModel = BusinessActivityModel(dic: dic)
                    
                    tempArray.append(tempModel)
                    
                    self!.dataModels!.append(tempModel)
                    
                }
                
                self!.cacheMorePictures(model: tempArray)
                
            }else{
                
//                self!.plainTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
    }
    
    
    
    
    func cachePictures(){
        
        
        let grop = DispatchGroup()
        
        for temp in dataModels! {
            
            guard let url = URL(string: temp.article_cover) else {
                continue
                
            }
            
            grop.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                
                //                QL1("下载一张完成")
                
                grop.leave()
                
            })
            
        }
        
        
        
        grop.notify(queue: DispatchQueue.main) {
            
            
            //            QL1("全部下载完成，刷新UI")
            
//            self.plainTableView.mj_footer.resetNoMoreData()
            
            
            if self.hasmore == "0" {
                
//                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
            }
            
//            self.plainTableView.mj_header.endRefreshing()
            
            self.plainTableView.reloadData()
            self.groupTableView.reloadData()
            self.groupTableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .top)

        }
        
    }
    
    
    func cacheMorePictures(model : [BusinessActivityModel]){
        
        
        let grop = DispatchGroup()
        
        for temp in model {
            
            guard let url = URL(string: temp.article_cover) else {
                continue
            }
            
            grop.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                grop.leave()
                
            })
            
        }
        
        
        grop.notify(queue: DispatchQueue.main) {
            
            if self.hasmore == "0" {
                
                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
                
            }else{
                
                self.plainTableView.mj_footer.endRefreshing()
                
            }
            
            
            
            self.plainTableView.reloadData()
            
        }
        
        
    }
    
    
    
    
    
}




extension PeripheryServiceVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            
            return 0
        }
        
        if dataModels!.count > 0 {
            
            if tableView == groupTableView {
                return 1
            } else {
                return leftTitles.count
            }
            
            
        } else {
            
            return 0
            
        }
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataModels == nil {
            
            return 0
        }

        
        if tableView == groupTableView {
            return leftTitles.count
        } else {
            return strings.count
        }
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
//        
//        let tableCell : NearbyServiceCell =  tableView.dequeueReusableCell(withIdentifier: NearbyServiceCell.identifer()) as! NearbyServiceCell
//        
        //        let mode = dataModels?[indexPath.row]
        //
        //        mode?.article_title = strings[indexPath.row]
//        
//        tableCell.model = mode
        

        if tableView == groupTableView {
            
            let tableCell : NearbyServiceCell =  tableView.dequeueReusableCell(withIdentifier: NearbyServiceCell.identifer()) as! NearbyServiceCell
            
            

             tableCell.str = leftTitles[indexPath.row]
            
            return tableCell

        }else{
            let tableCell : ServiceRightCell =  tableView.dequeueReusableCell(withIdentifier: ServiceRightCell.identifer()) as! ServiceRightCell

            tableCell.textLabel?.text = strings[indexPath.row]
            
            return tableCell


        }
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if tableView == groupTableView {
            return 0.0001
        } else {
            return 36
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        if tableView == groupTableView {
            return 0.00001
        } else {
            return 0.00001
        }

        
    }
    

    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if tableView == groupTableView {
            
            return UIView()
            
        } else {
            
            
            let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: RightTabelHeaderView.identifer()) as! RightTabelHeaderView
            
            
            temp.labelText = leftTitles[section]
            
            
            return temp
        }
        
        
        
        
        
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView == groupTableView {
            
            tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
            
            let index = IndexPath(row: 0, section: indexPath.row)
            
            plainTableView.scrollToRow(at: index, at: .top, animated: true)
            


        }

    }
    
    
    
    
    
    // TableView 分区标题即将展示
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        // 当前的 tableView 是 RightTableView，RightTableView 滚动的方向向上，RightTableView 是用户拖拽而产生滚动的（（主要判断 RightTableView 用户拖拽而滚动的，还是点击 LeftTableView 而滚动的）
        if (plainTableView == tableView)
            && !isScrollDown
            && (plainTableView.isDragging || plainTableView.isDecelerating) {
            selectRow(index: section)
        }
    }
    
    // TableView分区标题展示结束
    func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
        // 当前的 tableView 是 RightTableView，RightTableView 滚动的方向向下，RightTableView 是用户拖拽而产生滚动的（（主要判断 RightTableView 用户拖拽而滚动的，还是点击 LeftTableView 而滚动的）
        if (plainTableView == tableView)
            && isScrollDown
            && (plainTableView.isDragging || plainTableView.isDecelerating) {
            selectRow(index: section + 1)
        }
    }
    
    // 当拖动右边 TableView 的时候，处理左边 TableView
     func selectRow(index : Int) {
        groupTableView.selectRow(at: IndexPath(row: index, section: 0), animated: true, scrollPosition: .middle)
    }
    

    
     func scrollToTop(section: Int, animated: Bool) {
        let headerRect = plainTableView.rect(forSection:section)
        let topOfHeader = CGPoint(x: 0, y: headerRect.origin.y - plainTableView.contentInset.top)
        plainTableView.setContentOffset(topOfHeader, animated: animated)
    }
    
    
    // 标记一下 RightTableView 的滚动方向，是向上还是向下
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let tableView = scrollView as! UITableView
        if plainTableView == tableView {
            isScrollDown = lastOffsetY < scrollView.contentOffset.y
            lastOffsetY = scrollView.contentOffset.y
        }
    }

    
    
}



